﻿#include "filestatistics.h"
#include <QFile>
#include <QTextStream>

FileStatistics::FileStatistics(const QDir &dir) {
    calculateStatistics(dir);
}

QVector<FileStat> FileStatistics::getResults() const {
    return results;
}

void FileStatistics::calculateStatistics(const QDir &dir) {
    QStringList filters;
    filters << "*.h" << "*.hpp" << "*.c" << "*.cpp";

    QFileInfoList files = dir.entryInfoList(filters, QDir::Files | QDir::NoSymLinks);
    for (const auto &file : files) {
        FileStat stat;
        stat.filePath = file.absoluteFilePath();
        stat.type = file.suffix();

        QFile f(stat.filePath);
        if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&f);
            int lineCount = 0;
            int charCount = 0;
            while (!in.atEnd()) {
                QString line = in.readLine();
                ++lineCount;
                charCount += line.size();
            }
            f.close();

            stat.lines = lineCount;
            stat.characters = charCount;
            results.append(stat);
        }
    }

    QFileInfoList dirs = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
    for (const auto &subDir : dirs) {
        calculateStatistics(QDir(subDir.absoluteFilePath()));
    }
}
